package com.guosen.zebra.framework.starter.ngx.internal.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.guosen.zebra.framework.starter.ngx.exception.NgxException;
import com.guosen.zebra.framework.starter.ngx.model.InvokeContext;
import com.guosen.zebra.framework.starter.ngx.model.ListParameter;
import com.guosen.zebra.framework.starter.ngx.model.ListResult;
import com.guosen.zebra.framework.starter.ngx.util.UrlEncodeDecoder;

import java.util.HashMap;
import java.util.Map;

public class UniNgxList {
    /**
     * 获取文件列表路径
     */
    private static final String LIST_PATH = "/UniExServices/restfulapi/%s%s";

    public ListResult execute(ListParameter listParameter, InvokeContext invokeContext) throws NgxException {
        String urlEncodeAccount = UrlEncodeDecoder.encode(invokeContext.getAccount());
        String urlEncodePath = UniNgxUtil.urlEncodePath(listParameter.getPath());
        String listPath = String.format(LIST_PATH, urlEncodeAccount, urlEncodePath);

        String url = invokeContext.getAddress() + listPath;
        Map<String, String> headers = UniNgxUtil.buildHeaders(invokeContext);
        Map<String, String> parameters = buildListParameters(listParameter);

        JsonNode result = UniNgxRestfulClient.get(url, headers, parameters);
        UniNgxUtil.raiseExceptionIfExist(result);
        try {
            return UniNgxUtil.getObjectMapper().treeToValue(result, ListResult.class);
        } catch (JsonProcessingException e) {
            throw new NgxException(e);
        }
    }

    private Map<String, String> buildListParameters(ListParameter listParameter) {
        Map<String, String> parameters = new HashMap<>();
        UniNgxUtil.addParameter(parameters, "method", "list");
        UniNgxUtil.addParameter(parameters, "location", listParameter.getLocation().getVal());
        UniNgxUtil.addParameter(parameters, "is_dir", listParameter.getIsDir());
        UniNgxUtil.addParameter(parameters, "page", listParameter.getPage());
        UniNgxUtil.addParameter(parameters, "page_size", listParameter.getPageSize());
        UniNgxUtil.addParameter(parameters, "sort_by", listParameter.getSortBy());
        if (listParameter.getQueryChild() != null) {
            UniNgxUtil.addParameter(parameters, "browseFlag", 3);
        }
        return parameters;
    }
}
